package com.woniu.controller;

import com.woniu.been.entity.Teachers;
import com.woniu.been.entity.vo.TeachersVo;
import com.woniu.service.TeachersService;
import com.woniu.utils.PageResult;
import com.woniu.utils.ResponseResult;
import com.woniu.utils.SendSMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/TeachersController")
@CrossOrigin
public class TeachersController {
    @Autowired
    private TeachersService teachersService;
    @Autowired
    private RedisTemplate redisTemplate;

    /*
     * 老师或超级管理员账号密码登录
     * */
    @PostMapping("login")
    public ResponseResult<TeachersVo> login(@RequestBody Teachers teachers){
        System.out.println("登录"+teachers);
        Teachers teachersInfo = teachersService.login(teachers.getTeacherName(), teachers.getPassword());
        if(teachersInfo!=null){
            TeachersVo newteachers = new TeachersVo(teachersInfo.getTeacherId(), teachersInfo.getTeacherName());
            return ResponseResult.success(newteachers);
        }
        return ResponseResult.fail(500,"用户名或密码错误");
    }
    /*
     *老师或超级管理员账手机号登录------获取验证码
     * */
    @PostMapping("phoneLogin")
    public ResponseResult<TeachersVo> phoneLogin(@RequestBody Teachers teachers) throws Exception {
        //根据手机号找到该对象并保存验证码（只传入了手机号码 老师名为null）
        List<Teachers> teachersInfo = teachersService.findTeacherByNameAndTelephone(teachers.getTeacherName(), teachers.getTelephone());
        System.out.println(teachersInfo);
        if(teachersInfo != null && !teachersInfo.isEmpty()){
            //随机生成验证码
            String code = SendSMSUtil.randomCode();
            //存储到Redis（5分钟过期）
            redisTemplate.opsForValue().set("sms:verify:" + teachers.getTelephone(), code, 5, TimeUnit.MINUTES);
            //调用对应工具类方法实现发送验证码
            SendSMSUtil.sendSMSMessage(teachers.getTelephone(), code, "阿里云短信测试", "SMS_154950909");

            return ResponseResult.success("验证码发送成功",null);
            }
        return ResponseResult.fail(500,"该手机号已被注册");
    }

        /*
         * 对比验证码是否正确 （登录和注册都可以调用该方法作为登录或注册的最后一步 登录按钮和注册按钮连接的接口）
         * */
        @PostMapping("checkCode")
        public  ResponseResult<TeachersVo> checkCode(@RequestBody Teachers teachers) {
            // 从Redis获取存储的验证码
            String code = (String) redisTemplate.opsForValue().get("sms:verify:" + teachers.getTelephone());
            //判断验证码是否正确 code是发送验证码时保存的 teachers.getCode()是从前端的表单中带回来的验证码
            if(teachers.getCode().equals(code)){
                //验证码正确
                List<Teachers> teachersInfo = teachersService.findTeacherByNameAndTelephone(teachers.getTeacherName(), teachers.getTelephone());
                if(teachersInfo != null && teachersInfo.isEmpty()){
                    //注册
                     teachersService.register(teachers);
                    return ResponseResult.success("注册成功",  null);
                }else{
                    //登录
                    TeachersVo loginTeachers = new TeachersVo(teachersInfo.get(0).getTeacherId(), teachersInfo.get(0).getTeacherName());
                    return ResponseResult.success("登录成功",loginTeachers);
                }
            }
            //验证码错误
            return ResponseResult.fail(500,"验证码错误");
        }

        /*
         * 添加老师信息--发送验证码
         * */
        @PostMapping("/register")
        public ResponseResult<Teachers> register(@RequestBody Teachers teachers) throws Exception {
            //判断用户名是否已存在
            List<Teachers> teachersInfo = teachersService.findTeacherByNameAndTelephone(teachers.getTeacherName(), teachers.getTelephone());
            if(teachersInfo != null && teachersInfo.isEmpty()){
                //随机生成验证码
                String code = SendSMSUtil.randomCode();
                //存储到Redis（5分钟过期）
                redisTemplate.opsForValue().set("sms:verify:" + teachers.getTelephone(), code, 5, TimeUnit.MINUTES);
                //调用对应工具类方法实现发送验证码
                SendSMSUtil.sendSMSMessage(teachers.getTelephone(), code, "阿里云短信测试", "SMS_154950909");
                return ResponseResult.success("验证码发送成功",null);
            }
            return ResponseResult.fail(500,"用户已存在");
        }

        /*
         * 动态查询所有老师并进行分页
         * */
        @PostMapping("findAllTeacher")
        public ResponseResult<PageResult> findAllTeacher(@RequestBody TeachersVo teacherVo){
            PageResult result = teachersService.findAllTeacher(teacherVo, teacherVo.getPageNum(), teacherVo.getPageSize());
            return ResponseResult.success(result);
        }
        /*
         * 删除老师信息
         * */
        @DeleteMapping("deleteTeacher")
        public ResponseResult<Void> deleteTeacher(Integer teacherId){
            teachersService.deleteTeacher(teacherId);
            return ResponseResult.success();
        }
        /*
         * 修改老师信息 ----  添加修改人 以及 修改时间
         * */
        @PutMapping("updateTeacher")
        public ResponseResult<Void> updateTeacher(@RequestBody Teachers teachers){
            System.out.println("updateTeacher========================="+ teachers);
            // 判断用户名或电话是否已存在（排除自己）
            List<Teachers> teachersInfo = teachersService.findTeacherNotContainItself(
                    teachers.getTeacherName(),
                    teachers.getTelephone(),
                    teachers.getTeacherId()
            );
            System.out.println("teachersInfo size==========================="+ teachersInfo);

            // 修正：如果查询结果不为空（即存在重复教师），则拒绝修改
            if (!teachersInfo.isEmpty()){
                return ResponseResult.fail(500,"用户已存在");
            }
            // 没有重复教师，执行修改
            teachersService.updateTeacher(teachers);
            return ResponseResult.success();
        }

        /*
        * 根据老师姓名更改老师role
        * */
        @PutMapping("updateTeacherRole")
        public ResponseResult<Void> updateTeacherRole(@RequestBody Teachers teachers){
            System.out.println("updateTeacherRole========================="+ teachers);
            teachersService.updateTeacherRole(teachers.getTeacherName(), teachers.getRole());
            return ResponseResult.success();
        }
        /*
        * 根据老师姓名查询老师的身份
        * */
        @PostMapping("findTeacherRoleByTeacherName")
        public ResponseResult<String> findTeacherRoleByTeacherName(@RequestBody Teachers teachers){
            System.out.println("findTeacherRoleByTeacherName"+teachers);
            String role = teachersService.findTeacherRoleByTeacherName(teachers.getTeacherName());
            System.out.println("身份"+role);
            return ResponseResult.success(role);
        }

        /*
        * 根据老师手机号码查询老师的身份
        * */
        @PostMapping("findTeacherRoleByTelephone")
        public ResponseResult<String> findTeacherRoleByTelephone(@RequestBody Teachers teachers){
            String role = teachersService.findTeacherRoleByTelephone(teachers.getTelephone());
            return ResponseResult.success(role);
        }

        /*
         * 根据老师手机号码查询老师的姓名
         * */
        @PostMapping("findTeacherNameByTelephone")
        public ResponseResult<String> findTeacherNameByTelephone(@RequestBody Teachers teachers){
            String teacherName = teachersService.findTeacherNameByTelephone(teachers.getTelephone());
            return ResponseResult.success(teacherName);
        }

        /*
        * 添加管理员 -- 检验管理员发送的验证码是否正确
        * */
        @PostMapping("checkAdminCode")
        public  ResponseResult<TeachersVo> checkAdminCode(@RequestBody Teachers teachers) {
            // 从Redis获取存储的验证码
            String code = (String) redisTemplate.opsForValue().get("sms:verify:" + teachers.getTelephone());
            //判断验证码是否正确 code是发送验证码时保存的 teachers.getCode()是从前端的表单中带回来的验证码
            if(teachers.getCode().equals(code)){
                //注册
                teachersService.addAdmin(teachers);
                return ResponseResult.success("注册成功",  null);
            }
                //验证码错误
                return ResponseResult.fail(500,"验证码错误");
        }

        /*
        * 根据姓名查询老师信息
        * */
        @GetMapping("findTeacherByName")
        public ResponseResult<Teachers> findTeacherByName(@RequestParam String teacherName){
            System.out.println("findTeacherByName :"+teacherName);
            Teachers teachers = teachersService.findTeacherByName(teacherName);
            System.out.println("findTeacherByName  查询出来的老师信息:"+teachers);
            return ResponseResult.success(teachers);
        }

        /*
        * 上传修改头像
        * */
        @PostMapping("uploadFile")
        public ResponseResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("teacherName") String teacherName) throws IOException {
            System.out.println("上传文件"+file);
            System.out.println("名字"+teacherName);
            //1.定位文件上传保存基本路径
            String basePath = "D:\\img";
            //2.定义访问图片网络url基础路径
            String baseUrl = "http://localhost:80/";
            //3.获取文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")) ;
            //4.随机一个文件名称
            long prefix = new Date().getTime();
            //5.生成文件名称
            String filename = prefix + suffix;
            //6.把文件保存到指定位置
            file.transferTo(new File(basePath, filename));

            String imagePath = baseUrl + filename;
            //7.把文件地址保存到数据
            teachersService.updateByUsername(imagePath,teacherName);
            //封装数据响应给前端
            return ResponseResult.success(imagePath);
        }

        /*
        * 根据id查询老师信息
        * */
        @GetMapping("findTeacherById")
        public ResponseResult<Teachers> findTeacherById(@RequestParam Integer teacherId){
            System.out.println("teacherId ==================================================================:"+teacherId);
            Teachers teachers = teachersService.findTeacherById(teacherId);
            System.out.println("teachers ==================================================================:"+teachers);
            return ResponseResult.success(teachers);
        }
}

